package com.huilian.iotbox.admin.controller;

import com.huilian.iotbox.admin.service.StatsStoreService;
import com.huilian.iotbox.admin.service.UserService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.controller.BaseController;
import com.huilian.iotbox.data.dto.LotteryRecordDto;
import com.huilian.iotbox.data.dto.StatsStoreDto;
import com.huilian.iotbox.data.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

/**
 * @author lizhiquan
 * @CreateDate: 2021-04-13 16:59
 * @Description:
 */
@RestController
@RequestMapping("/api/statsStore")
public class StatsStoreController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private StatsStoreService statsStoreService;

    @PostMapping("/list")
    public ServerResponse list(HttpServletRequest request, @RequestBody StatsStoreDto statsStoreDto) {
        String pageNum =  request.getParameter("pageNum");
        String pageSize =  request.getParameter("pageSize");
        UserInfo userInfo = userService.getLoginUserInfo(request);
        statsStoreDto.setUserInfo(userInfo);
        statsStoreDto.setPageNum(Integer.parseInt(pageNum));
        statsStoreDto.setPageSize(Integer.parseInt(pageSize));
        return ServerResponse.createBySuccess(statsStoreService.findList(statsStoreDto));
    }

    @PostMapping("/exportStatsStoreList")
    public ServerResponse exportStatsStoreList(HttpServletRequest request, @RequestBody StatsStoreDto statsStoreDto) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        statsStoreDto.setUserInfo(userInfo);
        if(statsStoreDto.getCreateTime()==null){
            return ServerResponse.createByErrorMessage("请求异常，导出时间间隔建议在一个月内");
        }
        boolean flag = compareReqTimeSectionMonth(statsStoreDto.getCreateTime(),statsStoreDto.getUpdateTime());
        if(!flag){
            return ServerResponse.createByErrorMessage("请求异常，导出时间间隔建议在一个月内");
        }
        return statsStoreService.exportStatsStoreList(statsStoreDto);
    }

    private boolean compareReqTimeSectionMonth(Date beginTime, Date endTime) {
        Calendar calendar = Calendar.getInstance(); // 得到日历
        if (beginTime == null) {
            return false;
        }
        calendar.setTime(beginTime); // 把当前时间赋给日历
        calendar.add(Calendar.MONTH, 1); // 添加一个月
        beginTime = calendar.getTime();
        int i = beginTime.compareTo(endTime);
        return i >= 0;
    }
}
